package com.runa.protocol.analysis;

import com.runa.protocol.dto.DtuReport;

public class Dtu86BufferAnalysis extends ShellBufferAnalysis<byte[]> {

    public Dtu86BufferAnalysis(MetaBufferAnalysis analysis) {
        super(analysis, 1024);
    }

    @Override
    public int fill(byte[] data, int length,String netEquNo) {
        interData = null;
        int begin;
        for (begin = 0; begin < length; begin++) {
            if ((data[begin]&0xff) == 0x5B) {
                if ((data[begin + 1]&0xff) == 0x5B) begin++;
                break;
            }
        }
        int end;
        for (end = begin; end < length; end++) {
            if ((data[end]&0xff) == 0x5B) break;
        }
        if (end - begin < 7) return -1;
        int code = data[begin + 1] & 0xff;
        if (code == 0) {
            byte[] ids = new byte[11];
            ids[0] = (byte)(0x30 + ((data[begin + 2]&0xF0)>>4));
            ids[1] = (byte)(0x30 + (data[begin + 2]&0x0F));
            ids[2] = (byte)(0x30 + ((data[begin + 3]&0xF0)>>4));
            ids[3] = (byte)(0x30 + (data[begin + 3]&0x0F));
            ids[4] = (byte)(0x30 + ((data[begin + 4]&0xF0)>>4));
            ids[5] = (byte)(0x30 + (data[begin + 4]&0x0F));
            ids[6] = (byte)(0x30 + ((data[begin + 5]&0xF0)>>4));
            ids[7] = (byte)(0x30 + (data[begin + 5]&0x0F));
            ids[8] = (byte)(0x30 + ((data[begin + 6]&0xF0)>>4));
            ids[9] = (byte)(0x30 + (data[begin + 6]&0x0F));
            ids[10] = (byte)(0x30 + ((data[begin + 7]&0xF0)>>4));
            String id = new String(ids);
            netEquNo = id;
            interData = new DtuReport(id);
        } else if (code == 2) {
            int size = end - begin - 8;
            if (size > buffer.length) expand(size);
            System.arraycopy(data, begin+8, buffer, 0, size);
            analysis.fill(buffer, size,netEquNo);
            interData = analysis.gain();
        }
        return 0;
    }
}
